package zhr.chapter8.remixCalApp;

import java.util.LinkedList;

public class Expression extends LinkedList<NumSign> {
    public String toString(){
        String str="";
        for(NumSign numSign:this){
            str=str+numSign.getStrNum()+numSign.getSign();
        }
        return str;
    }
    public double calculate(){
        calMulAndDiv();
        calAddAndSub();
        return this.get(0).getNum();
    }
    private void calMulAndDiv(){
        for(int i=0;i<this.size();i++){
            System.out.println(this.toString());
            if(this.size()==1)return;
            if(this.get(i).getSign()=='*'){
                double temp=this.get(i).getNum()*this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
            if(this.get(i).getSign()=='/'){
                double temp=this.get(i).getNum()/this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
        }
    }
    private void calAddAndSub(){
        for(int i=0;i<this.size();i++){
            System.out.println(this.toString());
            if(this.size()==1)return;
            if(this.get(i).getSign()=='+'){
                double temp=this.get(i).getNum()+this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
            if(this.get(i).getSign()=='-'){
                double temp=this.get(i).getNum()-this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
        }
    }
}
